// 帖子操作API函数
import request from './request.js'
import { API_ENDPOINTS } from './api.js'
import { getCurrentUserId } from './auth.js'

// 获取帖子列表
export const getPosts = async () => {
  try {
    const response = await request.get(API_ENDPOINTS.POSTS.LIST)
    return response.data.data
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    throw error
  }
}

// 获取帖子详情
export const getPostDetail = async (postId) => {
  try {
    const response = await request.get(API_ENDPOINTS.POSTS.DETAIL(postId))
    return response.data
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    throw error
  }
}

// 点赞/取消点赞
export const toggleLike = async (postId, action) => {
  try {
    const response = await request.post(API_ENDPOINTS.POSTS.LIKE(postId), {
      action, // 'like' 或 'unlike'
      user_id: getCurrentUserId()
    })
    return response.data
  } catch (error) {
    console.error('点赞操作失败:', error)
    throw error
  }
}

// 收藏/取消收藏
export const toggleStar = async (postId, action) => {
  try {
    const response = await request.post(API_ENDPOINTS.POSTS.STAR(postId), {
      action, // 'star' 或 'unstar'
      user_id: getCurrentUserId()
    })
    return response.data
  } catch (error) {
    console.error('收藏操作失败:', error)
    throw error
  }
} 

// 获取评论列表
export const getComments = async (postId) => {
  try {
    const response = await request.get(API_ENDPOINTS.COMMENTS.BY_POST(postId))
    return response.data.data
  } catch (error) {
    console.error('获取评论列表失败:', error)
    throw error
  }
}

// 创建评论
export const createComment = async (postId, content) => {
  try {
    const response = await request.post(API_ENDPOINTS.COMMENTS.CREATE, {
      post: postId,
      content,
      user_id: getCurrentUserId()
    })
    return response.data
  } catch (error) {
    console.error('创建评论失败:', error)
    throw error
  }
}

// 删除评论
export const deleteComment = async (commentId) => {
  try {
    const response = await request.delete(API_ENDPOINTS.COMMENTS.DELETE(commentId))
    return response.data
  } catch (error) {
    console.error('删除评论失败:', error)
    throw error
  }
}

// 获取用户操作状态
export const getUserActions = async (userId) => {
  try {
    const response = await request.get(`${API_ENDPOINTS.USER_ACTIONS.GET}?user_id=${userId}`)
    return response.data
  } catch (error) {
    console.error('获取用户操作状态失败:', error)
    throw error
  }
}

// 同步用户操作
export const syncUserActions = async (userId, actions) => {
  try {
    const response = await request.post(API_ENDPOINTS.USER_ACTIONS.SYNC, {
      user_id: userId,
      actions
    })
    return response.data
  } catch (error) {
    console.error('同步用户操作失败:', error)
    throw error
  }
} 